package com.smartwebx.ha.web.admin.common;

import static com.alibaba.citrus.util.Assert.assertNotNull;
import static com.alibaba.citrus.util.Assert.assertTrue;
import static com.alibaba.citrus.util.BasicConstant.EMPTY_STRING_ARRAY;
import static com.alibaba.citrus.util.ObjectUtil.defaultIfNull;
import static com.alibaba.citrus.util.StringUtil.join;
import static com.alibaba.citrus.util.StringUtil.trimToNull;

import java.io.Serializable;

import com.alibaba.citrus.util.Assert.ExceptionType;
import com.alibaba.citrus.util.ObjectUtil;
import com.google.common.base.Objects;

public class HaUser implements Serializable {
	private static final long serialVersionUID = -7507510429755782596L;
	private static final ThreadLocal<HaUser> userHolder = new ThreadLocal<HaUser>();
	private Integer id;
	private String userId;
	private String[] roles;

	public static final HaUser getCurrentUser() {
		return userHolder.get();
	}

	public static final void setCurrentUser(HaUser user) {
		userHolder.set(user);
	}

	/** 创建匿名用户。 */
	public HaUser() {
	}

	/** 创建用户。 */
	public HaUser(String userId, Integer id) {
		this.userId = trimToNull(userId);
		this.id = ObjectUtil.defaultIfNull(id, -1);
	}

	public String getName() {
		return userId;
	}

	public Integer getId() {
		return id;
	}

	public String[] getRoles() {
		return defaultIfNull(roles, EMPTY_STRING_ARRAY);
	}

	public void setRoles(String[] roles) {
		this.roles = roles;
	}

	public void upgrade(Integer id, String userId, String[] roles) {
		assertTrue(!hasLoggedIn(), ExceptionType.ILLEGAL_STATE,
				"already logged in");

		userId = assertNotNull(trimToNull(userId), "no user id");

		this.userId = userId;
		this.roles = roles;
		this.id = ObjectUtil.defaultIfNull(id, -1);
	}

	public boolean hasLoggedIn() {
		return userId != null && id != -1;
	}

	@Override
	public String toString() {
		return Objects.toStringHelper(HaUser.class).add("id", id)
				.add("userId", defaultIfNull(userId, "anonymous"))
				.add("roles", join(getRoles(), ":")).toString();
	}
}
